********************************************************************************
*   Title: programs_kinky.do
* Purpose: Project specific programs
* Authors: Qiping Xu, Eric Zwick
*     RAs: Tom (Tianfang) Cui, Laurence O'Brien, Harleen Kaur,
* 		   Francesco Ruggieri, Caleb Wroblewski, Ramiro Rossi
*    Date: 2024-05-02
********************************************************************************

capture program drop load_analysis_data /* %< */
program define load_analysis_data
    syntax anything(name=id), [datadir(string) QUART(numlist)]
	
    if "`datadir'" == "" local datadir "$analysis"

    if "`id'" == "capx_trim5" {
        use "`datadir'/capxannual_trim5.dta", clear
		replace capx4_3 = capx4_3 * 100
    }
    else if "`id'" == "capx_trim5_short" {
        use "`datadir'/capxannual_trim5_short.dta", clear
    }
	else if "`id'" == "quarterly_capx" {
	    use "`datadir'/capxannual_trim5.dta", clear
		keep gvkey fyear
		merge 1:n gvkey fyear using "$intermediate/quarterlydata.dta", keep(3)
	}
	else if "`id'" == "fyrchange" {
        use "`datadir'/capxannual_trim5.dta", clear
		bysort gvkey: egen maxmonth = max(cal_month)
		bysort gvkey: egen minmonth = min(cal_month)
		keep if maxmonth != minmonth & minmonth != . & maxmonth != .
		bysort gvkey: gen dif = d.fyrend_month
		gen change_ind = 1 if dif != 12 & dif != .
		keep gvkey fyear  dif change_ind  fyrend_month capx
		tempfile fyrchange
		save "`fyrchange'"

		use "$intermediate/quarterlydata.dta", clear
		drop if fyear < 1984
		drop if fyear == .
		merge n:1 gvkey fyear using "`fyrchange'"
		keep if _merge == 3
		drop _merge
	}
	else if "`id'" == "capx_winsor3" {
        use "`datadir'/capxannual_winsor3.dta", clear
    }
    else if "`id'" == "capx" { 
        use "`datadir'/capxannual.dta", clear
    }
    else if "`id'" == "lending" {
        use "`datadir'/leases_and_loans.dta", clear
    }
    else if "`id'" == "quarterly" {
        use "`datadir'/response.dta", clear
    }
    else if "`id'" == "capxq" {
        use "`datadir'/capxq.dta", clear
    }
    else if "`id'" == "international" {
        use "`datadir'/international_trim5.dta", clear
    }
    else if "`id'" == "segment" {
        use "`datadir'/segmentdis.dta", clear
    }
    else if "`id'" == "rd" {
        use "`datadir'/rddecomp.dta", clear
    }
    else if "`id'" == "m3" {
        use "`datadir'/M3 Survey/sic.dta", clear

        drop if year > 1991
        replace industry = "COG" if industry == "COS"
        replace industry = "33E" if industry == "35M"
		replace industry = "IEM" if industry == "33E" 
        append using "`datadir'/M3 Survey/naics.dta"
        keep if s_adjusted=="U"
	    keep if industry == "TCG" | industry == "NDE" | industry == "COG"
        foreach x in fi mi ti wi uo no vs {
            bysort industry year: egen `x'_m = mean(`x')
            gen `x'_n = `x'/`x'_m * 100
            drop `x'_m
        }
        drop if year==2017
		
		
        /*industrial manufacturing 33E
            Capital goods: TCG 
            NDE Nondefense Capital Goods
            NXA Nondefense Capital Goods Excluding Aircraft
            COG Consumer Goods
            CDG Consumer Durable Goods
            CNG Consumer Nondurable Goods
        */
    }
	else if "`id'" == "cumlevel_all" {
		use "`datadir'/q1event", clear
		append using "`datadir'/q2event"
		append using "`datadir'/q3event"
		append using "`datadir'/q4event"		
	}
	else if "`id'" == "responseq4" {
		use "`datadir'/responseq4", clear
	}
	else if "`id'" == "m3_ppi_nde" {
		use "`datadir'/M3 Survey/naics.dta", clear
		keep if s_adjusted == "U"
		keep if industry == "NDE"
		foreach x in fi mi ti wi uo no vs is us {
			bysort industry year: egen `x'_m = mean(`x')
			gen `x'_ratio_NDE = (`x'/`x'_m) * 100
			drop `x'_m
		}
		collapse vs_ratio ti_ratio uo_ratio no_ratio, by(industry month)
		tempfile nde
		save "`nde'"

		use "$intermediate/ppi_m3", clear
		collapse ppi_ratio *ratio_m3industry ///
			(sum) uo_m3industry no_m3industry vs_m3industry, ///
			by(m3industry time year month)

		drop fi_ratio_m3industry mi_ratio_m3industry wi_ratio_m3industry ///
			 is_ratio_m3industry us_ratio_m3industry
		bysort time: egen totalvs = total(vs_m3industry)
		gen vsratio = vs_m3industry / totalvs
		gen ppi_ratio_vw = ppi_ratio * vsratio
		collapse ppi_ratio (sum) ppi_ratio_vw, by(time year month)
		collapse ppi_ratio ppi_ratio_vw, by(month)
		merge 1:1 month using "`nde'", nogen
	}
	else if "`id'" == "supplier" {
		use "`datadir'/capxannual", clear
		keep gvkey fyear capx4_3 capxq1 capxq2 capxq3 capxq4 capxy1 capxy2 capxy3 capxy4
		foreach x in capx* {
			rename `x' c_`x'
		}
		rename c_capx4_3 c_capx43
		tempfile customer
		save "`customer'"

		use "`datadir'/capxannual", clear
		keep gvkey fyear fyrend_month
		rename gvkey s_gvkey
		tempfile fyearmonth
		save "`fyearmonth'"

		use "`datadir'/Compustat/customer_segment_link", clear
		rename gvkey s_gvkey
		rename cgvkey c_gvkey
		destring s_gvkey, replace
		destring c_gvkey, replace
		gen fyrend_month = ym(year(srcdate), month(srcdate))
		drop if year(srcdate) < 1983 | year(srcdate) > 2016
		merge n:1 s_gvkey fyrend_month using "`fyearmonth'", keep(3) nogen
		drop if fyear == .
		order s_gvkey c_gvkey srcdate fyrend_month
		sort s_gvkey c_gvkey srcdate 

		rename salecs customer_sale

		rename c_gvkey gvkey
		merge n:1 fyear gvkey using "`customer'", nogen keep(1 3)
		rename gvkey c_gvkey
		rename s_gvkey gvkey
		merge n:1 gvkey fyear using "`datadir'/capxannual", nogen keep(3)
		order gvkey fyear sale c_gvkey customer_sale c_capx43
		gsort gvkey fyear sale c_gvkey  customer_sale c_capx43
	}
	else if "`id'" == "loanrate" {
		use "`datadir'/loanrate_data", clear
	}
	else if "`id'" == "RateWatch" {
		foreach z in  commequp250k commoper50k  commreal1mil  personalunsec{
			use "`datadir'/RateWatch/`z'.dta", clear
			drop if year<2005|year>2016
			collapse rate (median) medrate=rate (count) ///
					 countrate=rate, by(loanmonth year month)
			winsor2 rate medrate, replace cut(1 99)
			
			foreach x in rate medrate{
				bysort year: egen ave`x'=mean(`x')
				replace `x'=`x'*100/ave`x'
			}
			
			su rate medrate, de
			rename medrate med`z'
			rename rate `z'
			rename countrate count`z'
			tab count`z'
			collapse `z' med`z', by(month)
			la var `z' "`z'"
			tempfile r`z'
			save "`r`z''"
		}	
		
		use "`rcommequp250k'", clear
		merge 1:1 month using  "`rcommoper50k'", nogen
		merge 1:1 month using  "`rcommreal1mil'", nogen
		merge 1:1 month using "`rpersonalunsec'", nogen
	}
	else if "`id'" == "ppi_table" {
		
		use  "`datadir'/M3 Survey/naics.dta", clear
		keep if s_adjusted == "U"
		foreach x in fi mi ti wi uo no vs is us {
			bysort industry year: egen `x'_m = mean(`x')
			gen `x'_ratio=`x' / `x'_m * 100
			drop `x'_m
		}
		tempfile m3naics
		save "`m3naics'"
		
		use "`datadir'/BLS_PPI/Data/ppinaics6.dta", clear
		drop product_code industry_name
		gen time = ym(year, month)
		format time %tm
		bysort naics6: egen mintime = min(time)
		bysort naics6: gen base = ppi if time == mintime
		bysort naics6: egen baseppi = max(base)
		order naics6 year month ppi baseppi 
		replace ppi = ppi / baseppi * 100
		drop base mintime baseppi ave_ppi
		 
		merge n:1 naics6 using "`datadir'/M3 Survey/ppi_m3_link.dta", keep(3) nogen 
		merge n:1 industry year month using "`m3naics'", keep(3) nogen
		drop s_adjusted 
		drop if year == 2017
		order industry naics6 year month time ppi* vs ti 
		collapse ppi ppi_ratio vs ti ti_ratio vs_ratio, by(industry time year month)
	}
	else if "`id'" == "accountingy" {
		use "`datadir'/Compustat/accountingy.dta", clear
		drop if fyear < 1984 | fyear > 2016
		drop if ff12 == 11 | ff12 == 8 
		drop if at < 10 | at == .			
	}
	else if "`id'" == "losses" {
	    insheet using "`datadir'/IRS/losses_20191218.csv", comma clear
	}
	else if "`id'" == "model" {
		
		tempfile ov hycta full full_tax21 full_tax46 full_depr06 full_depr18 full_taxcredit full_beta09725
		
		* Baseline
		use "`datadir'/model/allvars_panel_ov_beta975", clear
		gen version = "ov_beta975"
		save `ov'
		
		* Depreciation motive
		use "`datadir'/model/allvars_panel_hycta_beta975", clear
		gen version = "hycta_beta975"
		save `hycta'
		
		* Full versions
		* Ramiro added full_beta09725
		use "`datadir'/model/allvars_panel_full_beta975", clear
		gen version = "full_beta975"
		save `full'
		use "`datadir'/model/allvars_panel_full_beta975_tax21", clear
		gen version = "full_beta975_tax21"
		save `full_tax21'
		use "`datadir'/model/allvars_panel_full_beta975_tax46", clear
		gen version = "full_beta975_tax46"
		save `full_tax46'
		use "`datadir'/model/allvars_panel_full_beta975_depr06", clear
		gen version = "full_beta975_depr06"
		save `full_depr06'
		use "`datadir'/model/allvars_panel_full_beta975_depr18", clear
		gen version = "full_beta975_depr18"
		save `full_depr18'
		use "`datadir'/model/allvars_panel_full_beta975_taxcredit", clear
		gen version = "full_beta975_taxcredit"
		save `full_taxcredit'
		use "`datadir'/model/allvars_panel_full_beta09725", clear
		gen version = "full_beta09725"
		save `full_beta09725'
		
		append using `ov'
		append using `hycta'
		append using `full'
		append using `full_tax21'
		append using `full_tax46'
		append using `full_depr06'
		append using `full_depr18'		
		append using `full_taxcredit'		
		append using `full_beta09725'		
	}
	else if "`id'" == "model_eventtime" {
	    use "`datadir'/model/event_time_inv", clear
	}
    else if "`id'" == "model_drift" {

		tempfile  inflation drift full
		
		* Negative drift 
		use "`datadir'/model/drift/allvars_panel_full_inflation2", clear
        count
		gen version = "inflation"
		save `inflation'
		
		* Positive drift
		use "`datadir'/model/drift/allvars_panel_full_drift2", clear
        count
		gen version = "drift"
		save `drift'
		
		* Full versions
		use "`datadir'/model/drift/allvars_panel_full_beta975", clear
        count
		gen version = "full_beta975"
		save `full'
		
		append using `inflation'
		append using `drift'
		append using `full'
    }
    else if "`id'" == "taxable_rd" {
        insheet using "`datadir'/IRS/taxable_rd_20200113.csv", comma clear
    }
    else if "`id'" == "taxable_nolstock" {
        insheet using "`datadir'/IRS/taxable_rd_nolstock_20200113.csv", comma clear
    }
    else if "`id'" == "bunch_mean" {
        insheet using "`datadir'/IRS/ebitda2atmean_loss.csv", tab clear
    }
    else if "`id'" == "bunch_sd" {
        insheet using "`datadir'/IRS/ebitda2atsd_loss.csv", tab clear
    }
    else if "`id'" == "bunch_early" {
        insheet using "`datadir'/IRS/prop_future_bunch_early.csv", comma clear
    }
    else if "`id'" == "bunch_late" {
        insheet using "`datadir'/IRS/prop_future_bunch_late.csv", comma clear
    }
    else if "`id'" == "model_did" {
        use "`datadir'/model/did_panel_quarter", clear
    }
    else if "`id'" == "cum_bandwidth_app" {
        insheet using "`datadir'/IRS/cum_bandwidth_20240103.csv", comma clear
    }

end /* %> */

capture program drop trim_tails /* %< */
program define trim_tails
    syntax varlist, level(real) [TRIM]
    foreach x of varlist `varlist' {
        rename `x' `x'_ut
        winsor `x'_ut, generate(`x') p(`level')
        gen `x'_tr = cond(`x' == `x'_ut, `x'_ut, .)
        if "`trim'" != "" rename (`x'_tr `x') (`x' `x'_w)
    }
end /* %> */

capture program drop var_cumul /* %< */
program define var_cumul
    syntax varlist, qvar(varname)
    
    * NOTE: This should only be used on quarterly data
    confirm variable `qvar'
    foreach var of local varlist {
        confirm variable `var'q
        replace `var'y=`var'q  if  (`qvar'==1&`var'y==.)
        replace `var'y=`var'q+l.`var'q if (`qvar'==2&`var'y==.)
        replace `var'y=`var'q+l.`var'q+ l2.`var'q if  (`qvar'==3&`var'y==.) 
        replace `var'y=`var'q+l.`var'q+ l2.`var'q+ l3.`var'q if (`qvar'==4&`var'y==.) 
    }
end /* %> */

capture program drop qvar_prep /* %< */
program define qvar_prep
    syntax namelist(max=1 name=yvar), [auxvars(namelist)] [noFILTER noGEN QUARTERLY]

    if "`filter'" == "" {
        drop if `yvar'q1==.|`yvar'q2==.|`yvar'q3==.|`yvar'q4==.|`yvar'==.|`yvar'<0.1
        drop if `yvar'q1<0|`yvar'q2<0|`yvar'q3<0|`yvar'q4<0
    }

    if "`gen'" == "" {
        keep gvkey fyear naics* `yvar' `yvar'q? `auxvars'
        gen ave`yvar' = `yvar'/4
        forv i=1/4 {
            gen q`i' = `yvar'q`i'/ave`yvar'
        }
        gen totalratio = q1 + q2 + q3 + q4
        su totalratio, de
        drop if totalratio != 4 
    }
	
	if "`quarterly'" == "quarterly" {
	    keep gvkey fyear
		merge 1:n gvkey fyear using quarterlydata.dta, keep(3)
		drop if capxq==.|capxq<0
		drop if fyear < 1984 | fyear > 2016
		winsor2 capxq, cut(1 99) replace 
		keep gvkey fyear fyearquarter fquarter capxq  
		tsset gvkey fyearquarter
		rename fyearquarter fqtr
		format fqtr %tq
		preserve
		collapse (median) capxq, by(fqtr)
		replace q=q*100
			forv j=99(4)239 {
				local spikes `spikes', `j'
		}
	}
end /* %> */

capture program drop qvar_plot /* %< */
program define qvar_plot, byable(onecall)
    syntax [if/], varlab(string) output(string) ///
        [YSCale(numlist) XSCale(numlist) XLABel(string) YLABel(string) MEAN xsize(real 5.5)]

    preserve
    if "`if'" != "" keep if `if'
    local gfunc median
    if "`mean'" != "" local gfunc mean

    collapse (`gfunc') q1 q2 q3 q4, by(fyear `_byvars')
    reshape long q, i(fyear `_byvars') j(quarter)
    gen fqtr=yq(fyear, quarter)
    sort `_byvars' fqtr
    format fqtr %tq
    replace q=q*100

    * Drop countries with fewer than 9 years of quarterly data
    if _by() {
        by fic: egen b = count(fyear)
        drop if b < 9*4
        drop b
    }

    forv j=99(4)239 {
        local spikes `spikes', `j'
    }
    if "`yscale'" != "" local yopt ysc(range(`yscale')) 
    if "`xscale'" != "" local xopt xsc(range(`xscale')) 
    if "`xlabel'" != "" local xl xlabel(`xlabel')
    if "`ylabel'" != "" local yl ylabel(`ylabel')
    if "`xsize'" != "" local xs xsize(`xsize')

    capture levelsof `_byvars', local(fics)
    #delimit ;
    if !_rc {;
    foreach i of local fics {;
        twoway (line q fqtr) (scatter q fqtr if inlist(fqtr `spikes'), mcolor(red))
            if fic=="`i'",
            ytitle("Ratio of Quarterly `varlab' to Average `varlab' % ")
            xtitle("Fiscal Quarter")  `yopt' `xopt' `xl' `yl' `xs' legend(off)
            graphregion(color(white) lwidth(large)) bgcolor(white);
        graph export "`output'_`i'.pdf", as(pdf) replace;
    };};
    else {;
        twoway (line q fqtr) (scatter q fqtr if inlist(fqtr `spikes'), mcolor(red)),
            ytitle("Ratio of Quarterly `varlab' to Average `varlab' % ")
            xtitle("Fiscal Quarter")  `yopt' `xopt' `xl' `yl' `xs' legend(off)
            graphregion(color(white) lwidth(large)) bgcolor(white);
        graph export "`output'", as(pdf) replace;
    };
    #delimit cr
end /* %> */

capture program drop uncertainty_prep /* %< */
program define uncertainty_prep
    syntax, winspct(real) [auxvar(varlist)]

    sort gvkey
    gen bigspike = capx4_3 > 170 & capx4_3 != .
    by gvkey: egen capx4_3m = mean(capx4_3)
    by gvkey: egen bigspikem = mean(bigspike)
    local xvar ebitda ebitda2at

    keep gvkey fyear capx4_3m capx4_3 bigspikem `xvar' `auxvar'
    foreach var of local xvar {
        foreach mom in sd mean median {
            by gvkey: egen `var'`mom' = `mom'(`var')
        }
        gen `var'_sdmean = `var'sd / `var'mean
        gen `var'_sdmedian = `var'sd / `var'median
    }
   
    trim_tails ebitda2atmean , level(`winspct')
    drop *_ut

end /* %> */

capture program drop cumlevel_denom /* %< */
program define cumlevel_denom
	//use this to define the denominator 
	gen pre = (dis < 0)
	bysort eventid: egen avecapxpre = mean(capx) if pre == 1
	bysort eventid: egen aveppepre = mean(ppent) if pre == 1
	order eventid dis capx ppent avecapxpre aveppepre  
	bysort eventid: egen capxpre = max(avecapxpre)
	bysort eventid: egen ppepre = max(aveppepre)
	order eventid dis capx ppent avecapxpre aveppepre capxpre ppepre
	gen capx2capxpre=capx / capxpre
	gen capx2ppepre=capx / ppepre
	winsor2 capx2capxpre capx2ppepre, cut(1 99) replace 
end /* %> */

capture program drop model_bootstrap /* %< */
program define model_bootstrap

 global seed = 3141592

    local period 0
    local obs_per_firm 10

    tempfile coeffs

    * Simple bootstrap
    forv i = 1/1000 {

        local seed = $seed + `i'
        set seed `seed'

        tempfile orig eventid
        tempfile hyc full ov
        use "$analysis/model/event_time_inv.dta", clear

        * Just trying to randomly sample some firms
        keep if version == "full_beta975"
        save `orig', replace

        duplicates drop event_id, force
        gen randid = runiform()
        drop if period < `period'
        *keep if randid < .5
        sort firm_no randid
        by firm_no: keep if _n <= `obs_per_firm'
        *duplicates drop firm_no, force
        keep event_id
        save `eventid', replace

        use `orig', clear
        merge m:1 event_id using `eventid', keep(3) nogen

        * 1. average investment by event_time
        sum inv
        local benchmark = `r(mean)'
        gen num_periods = event_time + 4
        sort firm_no event_id period
        by firm_no event_id: gen cumul_inv = sum(inv)
        gen cum_avg_inv = cumul_inv / num_periods
        by firm_no event_id: gen cumul_gos = sum(gos)
        gen cum_avg_gos = cumul_gos / num_periods
        by firm_no event_id: gen cumul_z = sum(z)
        gen cum_avg_z = cumul_z / num_periods

        gen inv_benchmark = inv / `benchmark'
        gen cum_inv_benchmark = cumul_inv / `benchmark'
        gen cum_avg_inv_benchmark = cum_avg_inv / `benchmark'

        * 2. #1 split by deciles in invratio
        xtile spike_bin = inv_spike, nq(10)
        xtile spike_bin_coarse = inv_spike, nq(2)
        save `full', replace

        use "$analysis/model/event_time_inv.dta", clear
        keep if version == "hycta_beta975"
        save `orig', replace 

        duplicates drop event_id, force
        gen randid = runiform()
        drop if period < `period'
        *keep if randid < .5
        sort firm_no randid
        by firm_no: keep if _n <= `obs_per_firm'
        *duplicates drop firm_no, force
        keep event_id
        save `eventid', replace

        use `orig', clear
        merge m:1 event_id using `eventid', keep(3) nogen

        * 1. average investment by event_time
        sum inv
        local benchmark = `r(mean)'
        gen num_periods = event_time + 4
        sort firm_no event_id period
        by firm_no event_id: gen cumul_inv = sum(inv)
        gen cum_avg_inv = cumul_inv / num_periods
        by firm_no event_id: gen cumul_gos = sum(gos)
        gen cum_avg_gos = cumul_gos / num_periods
        by firm_no event_id: gen cumul_z = sum(z)
        gen cum_avg_z = cumul_z / num_periods

        gen inv_benchmark = inv / `benchmark'
        gen cum_inv_benchmark = cumul_inv / `benchmark'
        gen cum_avg_inv_benchmark = cum_avg_inv / `benchmark'

        * 2. #1 split by deciles in invratio
        xtile spike_bin = inv_spike, nq(10)
        xtile spike_bin_coarse = inv_spike, nq(2)
        save `hyc', replace

        use "$analysis/model/event_time_inv.dta", clear
        keep if version == "ov_beta975"
        save `orig', replace 

        duplicates drop event_id, force
        gen randid = runiform()
        drop if period < `period'
        *keep if randid < .5
        sort firm_no randid
        by firm_no: keep if _n <= `obs_per_firm'
        *duplicates drop firm_no, force
        keep event_id
        save `eventid', replace

        use `orig', clear
        merge m:1 event_id using `eventid', keep(3) nogen

        * 1. average investment by event_time
        sum inv
        local benchmark = `r(mean)'
        gen num_periods = event_time + 4
        sort firm_no event_id period
        by firm_no event_id: gen cumul_inv = sum(inv)
        gen cum_avg_inv = cumul_inv / num_periods
        by firm_no event_id: gen cumul_gos = sum(gos)
        gen cum_avg_gos = cumul_gos / num_periods
        sum z
        local benchmark_z = `r(mean)'
        by firm_no event_id: gen cumul_z = sum(z)
        gen cum_avg_z = cumul_z / num_periods
        gen cum_avg_z_benchmark = cum_avg_z / `benchmark_z'

        gen inv_benchmark = inv / `benchmark'
        gen cum_inv_benchmark = cumul_inv / `benchmark'
        gen cum_avg_inv_benchmark = cum_avg_inv / `benchmark'

        * 2. #1 split by deciles in invratio
        xtile spike_bin = inv_spike, nq(10)
        xtile spike_bin_coarse = inv_spike, nq(2)
        save `ov', replace

        * Plot these regression coefficients downstream.
		* Idea is to condition on level of productivity and cumulative productivity,
        * then look at the cumulative effects in the depreciation only model versus
        * the full model. In the full model, profitability is less important for
        * cumulative effects, which reflects the additional option value motive. 
		* Conditioning on profitability, the full model has higher persistence 
        * than the baseline model.

        use `full', clear
        append using `hyc'
        append using `ov'
        gen spiker = spike_bin_coarse == 2
        replace spiker = 0 if version == "ov_beta975"
        replace spiker = 1 if version == "ov_beta975" & inv_spike >= 1

        egen z_group = group(z)
        local controls i.z_group c.inv_spike#i.event_time 

        ** No t-1
        reg cum_avg_inv_benchmark i.event_time `controls' if ///
            event_time > 0 & spiker == 1 & version == "full_beta975", vce(cluster firm_no)

        gen spike_coeff_full = .
        gen spike_se_full = .
        forvalues etime = 1/12 {
           replace spike_coeff_full = _b[`etime'.event_time] if event_time == `etime'
           replace spike_se_full = _se[`etime'.event_time] if event_time == `etime'
        }

        reg cum_avg_inv_benchmark i.event_time `controls' if ///
            event_time > 0 & spiker == 1 & version == "hycta_beta975", vce(cluster firm_no)

        gen spike_coeff_hycta = .
        gen spike_se_hycta = .
        forvalues etime = 1/12 {
           replace spike_coeff_hycta = _b[`etime'.event_time] if event_time == `etime'
           replace spike_se_hycta = _se[`etime'.event_time] if event_time == `etime'
        }

        reg cum_avg_inv_benchmark i.event_time `controls' if ///
            event_time > 0 & spiker == 1 & version == "ov_beta975", vce(cluster firm_no)

        gen spike_coeff_ov = .
        gen spike_se_ov = .
        forvalues etime = 1/12 {
           replace spike_coeff_ov = _b[`etime'.event_time] if event_time == `etime'
           replace spike_se_ov = _se[`etime'.event_time] if event_time == `etime'
        }

        collapse (max) spike_coeff* spike_se*, by(event_time)
        gen iteration = `i'

        if (`i' == 1) {
            save "$intermediate/simulation_bootstrap_20200517.dta", replace
        }
        else {
            append using "$intermediate/simulation_bootstrap_20200517.dta" 
            save "$intermediate/simulation_bootstrap_20200517.dta", replace
        }
    }
    use "$intermediate/simulation_bootstrap_20200517.dta", clear
end/*%>*/
